extends Node2D


@export var zombie_scene: PackedScene
@export var plant_scene: PackedScene
@export var pea_scene: PackedScene
var zombie_list = []
var plant_list = []
var friction = 0.1
var ground_pos: Vector2
var show_pos = Sprite2D.new()
var set_pos: Vector2
var ground_grid = []
var pos_x = 0
var pos_y = 0

# Called when the node enters the scene tree for the first time.
func _ready():
	ground_pos = $Ground.position - Vector2(1260, 540) + Vector2(458, 157)
	show_pos.texture = preload('res://res/plant/peashooter/show.png')
	show_pos.apply_scale(Vector2(0.5, 0.5))
	show_pos.self_modulate.a = 0.5
	add_child(show_pos)
	for y in range(8):
		ground_grid.append([])
		for x in range(12):
			ground_grid[y].append([0])

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	queue_redraw()

#func _draw():
	#draw_rect(Rect2(ground_pos.x, ground_pos.y, 1300, 870), 'black', false, 4)
	
var zombie_spawn_number = 0
func _input(event):
	if event is InputEventMouse and event.is_pressed():
		if event.button_index == 1:
			if ground_grid[pos_y][pos_x][0] == 0:
				var plant = plant_scene.instantiate()
				plant_list.append(plant)
				plant.position = set_pos
				plant.shoot.connect(shoot)
				add_child(plant)
				ground_grid[pos_y][pos_x][0] = 1
		elif event.button_index == 2:
			var zombie = zombie_scene.instantiate()
			zombie_list.append(zombie)
			zombie.position = event.position
			zombie.spawn_number = zombie_spawn_number
			zombie_spawn_number += 1
			add_child(zombie)
	elif event is InputEventMouseMotion:
		if ground_pos.x <= event.position.x and event.position.x <= ground_pos.x + 1295 \
		and ground_pos.y <= event.position.y and event.position.y <= ground_pos.y + 861:
			pos_x = int(event.position.x - ground_pos.x) / 108
			pos_y = int(event.position.y - ground_pos.y) / 108
			if ground_grid[pos_y][pos_x][0] == 0:
				show_pos.visible = true
				var x = pos_x * 108 + 55 + ground_pos.x
				var y = pos_y * 108 + 55 + ground_pos.y
				set_pos = Vector2(x, y)
				show_pos.position = set_pos
			else:
				show_pos.visible = false
		else:
			show_pos.visible = false
			

func shoot(position):
	var pea = pea_scene.instantiate()
	pea.position = position
	add_child(pea)
